/**
 * 2017-2-21 swy 修改 datetimeparser
 * 2017-2-22 swy 新增 rest.get rest.post rest.put rest.del
 */
var shieldWindowUI = new UIShieldWindow();
var showWindowUI = new UIShowWindow();
var searchFromUI = new UISearchFrom();
var dateTimeUI = new UIDateTime();
var EUI = {
		//更新DataGrid的列值
		updateCellForDataGrid:function($datagrid,rowIndex,field,value){
			$datagrid.siblings(".datagrid-view2").find("tr[datagrid-row-index='"+rowIndex+"']").first().find("td[field='" + field + "']").find("div").html(value);
		},
		shieldWindow:shieldWindowUI.shieldWindow,
		shieldTime:shieldWindowUI.shieldTime,
		start:shieldWindowUI.start,
		
		showWindow:showWindowUI.showWindow,
		closeWindow:showWindowUI.closeWindow,
		resizeWindow:showWindowUI.resizeWindow,
		
		clearFormForTreegrid:searchFromUI.clearFormForTreegrid,
		searchForTreegrid:searchFromUI.searchForTreegrid,
		clearFormForDatagrid:searchFromUI.clearFormForDatagrid,
		searchForDatagrid:searchFromUI.searchForDatagrid,	
		clearFormForDatalist:searchFromUI.clearFormForDatalist,
		searchForDatalist:searchFromUI.searchForDatalist,	
		dateformatter:dateTimeUI.dateformatter,
		dateparser:dateTimeUI.dateparser,
		datetimeformatter:dateTimeUI.datetimeformatter,
		datetimeparser:dateTimeUI.datetimeparser,
		timeformatter:dateTimeUI.timeformatter,
		timeparser:dateTimeUI.timeparser,		
		alert:function(title, msg, icon, fn){
			$.messager.alert(title, msg, icon, fn);
		},
		confirm:function(title, msg, fn){
			$.messager.confirm(title, msg, function(result){
		        if (result){
		        	if(fn) fn(result);
	        	}
		    });
		},
		prompt:function(title, msg, fn){
		  $.messager.prompt(title, msg, function(r){
                //if (r){
                	if(fn) fn(r);j
                //}
          });			
		},		
		/**
		 * 取得表格被选中的行
		 * @param dg 表格jquery对象
		 * @param param == getSelected or getSelections or getChecked
		 * @param nullmsg 没有行被选中的提示信息
		 */
		getDgSelectRow:function(dg,param,nullmsg){
			if(!nullmsg) nullmsg = '请选择一条记录';
			if('getSelected' == param){
				var row = dg.datagrid(param);
				if(!row){
					$.messager.alert('提示',nullmsg,'info');
					return false;	
				}
				return row;
			}
			if('getSelections' == param || 'getChecked' == param){
				var rows = dg.datagrid(param);
				if(rows.length==0){
					$.messager.alert('提示',nullmsg,'info');
					return false;	
				}
				return rows;
			}			
		},
		/**
		 * 根据树节点ID，重新加载节点
		 * @param treeId 
		 * @param id
		 */
		reloadTreeByNodeId:function(treeId,id){
			var tree = $(treeId);
			if(tree[0]){
				var select = tree.tree('getSelected');
		 		var node = tree.tree('find',id);
	    		if(node) {
	    			if(tree.tree('isLeaf',node.target)){
	    				var p = tree.tree('getParent',node.target); 
	    				if(p) node = p;
	    			}
	    		}
	    		if(!node){
	    			tree.tree('reload');		    			
	    		}
    			if(node){
    				
    				if(select){
    					var id = select.id;
    					tree.tree('options').onLoadSuccess = function(node, data){
    						select = $(this).tree('find',id);
    						if(select){//当刷新的是根节点select = null,当刷新的非根节点select 为当前选中的节点
								//$(this).tree('expandTo',select.target);
								$(this).tree('expand',select.target);
								$(this).tree('select',select.target);
    						}
    						//$(this).tree('options').onLoadSuccess = undefined;
    					}
    				}
    				
    				//根节点就是叶子节点
    				if(tree.tree('isLeaf',node.target)){
    					tree.tree('reload');
    				}else
    					tree.tree('reload',node.target);
    				
    			}
			}
		},
		/**
		 * 验证ajax响应结果
		 * 如果有异常提示异常，返回false
		 * @param data
		 * @param flag = true ? 提示成功 ： 不提示成功
		 * @param rollback 回调函数
		 * @returns {Boolean}
		 */
		validateAppResult:function (data,flag,rollback) {
			if(data==null || typeof(data) == "undefined" || ((typeof(data)=="string"&&data.indexOf("sessiontimeout.jsp")==-1)&&typeof(data.massage) == "undefined")){
				$.messager.alert('提示',"系统未知错误，可能没有找到post/get方法。");
				return false;
			}
			//超时处理
			if(typeof(data)=="string"&&data.indexOf("sessiontimeout.jsp")>0){
				$('body').append(data);
				return false
			}

			//是否后台代码正常执行，如果出现异常，就提示异常，结束方法.
			//如果有errorlvl，提示异常。
			if (data != null && typeof(data.errorlvl) != "undefined") {
				//$.messager.alert('提示',data.mes,data.lvl)
				$.messager.alert('提示',data.massage,data.errorlvl);
				return false;
			}
			if(flag){
				$.messager.alert('提示',data.massage,'info',function(){
					if(rollback) rollback();
				});
			}else{
				if(rollback) rollback();
			}
			return true;
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			if(errorThrown){
				if(console && console.log) console.log(XMLHttpRequest.responseText);
				$.messager.alert('系统异常提示',"可能由于网络问题导致请求超时了，您可以刷新页面重新登入。["+textStatus + ":" + errorThrown+"]",'warning',function(){
					$('body').append("<javascript>window.location.href='../sessiontimeout.jsp'</javascript>");
				});
			}else{
				$('body').append("<javascript>window.location.href='../sessiontimeout.jsp'</javascript>");
			}
		},
		post:function (url,data,rollback,datatype,mothed) {
			var params = {};
			if(!datatype) params.dataType = 'json';
			if(datatype=='jsonp'){
				if(url.indexOf('?')!=-1){
					url += "&callback=?";
				}else{
					url += "?callback=?";
				}
				params.url = url;
				params.dataType = 'jsonp';
				params.jsonp = 'jsonp';
				params.jsonpCallback = 'jsonp';
			}
	
			$.ajax($.extend({
				url:url,
				type:(mothed?mothed:'POST'),
				data:data,
				success:function(data, textStatus){
					if(rollback) rollback(data, textStatus);
				},
				error:EUI.error
			},params));
		},	
		get:function (url,data,rollback,datatype) {
			EUI.post(url,data,rollback,datatype,'GET');
		},	
		del:function (url,data,rollback,datatype) {
			EUI.post(url,data,rollback,datatype,'DELETE');
		},	
		put:function (url,data,rollback,datatype) {
			EUI.post(url,data,rollback,datatype,'PUT');
		},	
		rest:{
			del:function(url,data,rollback,datatype){
				$.ajax({
					type: "DELETE",
					url: url,
					data:data,
					contentType:'application/json',
					dataType: datatype?datatype:"json",
					success: function(data, textStatus, jqXHR){
						if(!data) data = {};
						if(rollback) rollback($.extend({},{massage:'操作成功'},data));
					},error:EUI.error
				});
			},
			post:function(url,data,rollback,datatype){
				$.ajax({
					type: "POST",
					url: url,
					data:data,
					contentType:'application/json',
					dataType: (datatype?datatype:"json"),
					success: function(data, textStatus, jqXHR){
						if(!data) data = {};
						if(rollback) rollback($.extend({},{massage:'操作成功'},data));
					},error:EUI.error
				});
			},
			get:function(url,data,rollback,datatype){
				$.ajax({
					type: "GET",
					url: url,
					data:data,
					dataType: datatype?datatype:"json",
					success: function(data, textStatus, jqXHR){
						if(rollback) rollback(data);
					},error:EUI.error
				});
			},
			put:function(url,data,rollback,datatype){
				$.ajax({
					type: "PUT",
					url: url,
					data:data,
					contentType:'application/json',
					dataType: datatype?datatype:"json",
					success: function(data, textStatus, jqXHR){
						if(!data) data = {};
						if(rollback) rollback($.extend({},{massage:'操作成功'},data));
					},error:EUI.error
				});
			}
		},
		submit:function (formid,url,rollback,onBeforeSubmit,error) {
			if(!$(formid).form('validate')){
				return;
			}
			
			var params = {}; //先取得 datagrid 的查询参数
			var fields =$(formid).serializeArray(); //自动序列化表单元素为JSON对象
/*			alert(JSON.stringify(fields));
			$.each( fields, function(i, field){
				if(field.value!='') params[field.name] = field.value; //设置查询参数
			});*/
			if(onBeforeSubmit) {
				$.each( fields, function(i, field){
					if(field.value!='') {
						if(params[field.name]){
							if(SWYUtil && SWYUtil.isArray(params[field.name])){
								params[field.name].push(field.value);
							}else{
								var values = [params[field.name],field.value];
								params[field.name] = values; //设置查询参数
							}
						}else{
							params[field.name] = field.value;
						}
					}
				});
				onBeforeSubmit(params);
				if(params){
					var items = [];
					for(var key in params){
						if(SWYUtil && SWYUtil.isArray(params[key])){
							$.each(params[key], function(i, value){
								var item = {};
								item.name = key;
								item.value = value;
								items.push(item);
							});
						}else{
							items.push({name:key,value:params[key]});
						}
					}
				}
				fields = items;
			}
			EUI.shieldWindow(1,'__window','数据保存中...');
			$.ajax({
				url:url,
				type:'POST',
				dataType:'json',
				data:fields,
				success:function(data, textStatus){
					EUI.shieldTime++;
					if(rollback) rollback(data,params);
				},
				error:function(XMLHttpRequest, textStatus, errorThrown){
					EUI.shieldTime++;
					if(error) error(XMLHttpRequest, textStatus, errorThrown);
					else{
						if(errorThrown)
						$.messager.alert('系统错误',"可能由于网络问题导致请求超时了，您可以刷新页面重新登入。["+textStatus + ":" + errorThrown+"]",'warning',function(){
							$('body').append("<javascript>window.location.href='../sessiontimeout.jsp'</javascript>");
						});
						
					}
						
				}
			});			
		},
		easyuiSubmit:function (formid,url,rollback,onBeforeSubmit) {
			if(!$(formid).form('validate')){
				return;
			}
			EUI.shieldWindow(1,'__window','数据保存中...');
			$(formid).form('submit', {
			    url:url,
			    onSubmit: function(param){
					if(onBeforeSubmit){
						onBeforeSubmit(param);
					} 
					return true;
			    },
			    success:function(data){
			    	EUI.shieldTime++;
					if(rollback) rollback(data);
			    }
			});
		},			
		//格式化可编辑表格中combobox的字段值
		//options = value,row,field,data,codeField,codeName
		formatterGridFieldValue:function (options){
			if(!options.codeField) options.codeField = 'codeValue';
			if(!options.codeName) options.codeName = 'codeName';
			var val = undefined;
			for(var i=0; i<options.data.length; i++){
				if (options.data[i][options.codeField] == options.value) { val = options.data[i][options.codeName]; break;}
			}	
			if(!val){
				for(var i=0; i<options.data.length; i++){
					if(options.data[i][options.codeField] == options.row[options.field])
					 {
						//options.row[options.field] = options.value2;
					 	val =  options.data[i][options.codeName];break;
					 }
				}
			}
			return nvl(val,options.value);	
		},
		//判断value==null || undefined || 0 ,返回默认defaultValue
		nvl:function(value,defaultValue){
			return value?value:defaultValue
		}
};

//遮罩进度窗口
function UIShieldWindow(){
	
	//进度
	this.shieldTime = 0;
	//运行进度遮罩窗口
	//time 总进度
	//id  窗口ID
	//msg 提示信息
	//rollback 回调函数
	this.shieldWindow = function(time,id,msg,rollback)
	{	
		this.shieldTime = 0;
		if(!msg) msg = '系统运行中...';
		
		if(time==-1){
			$.messager.progress({ 
    			title:'提示信息', 
    			msg:msg,
    			text:''
    		});	
			this.start(time,id);
		}else{
			
				var self = this;
				if(!id) id = 'shieldWindow';
				$('body').append("<div id='" + id + "'><table  width='100%'><tr><td align='center'><span class='c-label'>" + msg + "</span><div id='p"+id+"'  style='width:250px;'></div></td></tr></table></div>");
				$('#'+id).window({
					title:'提示信息',
					width:300,
					height:100,
					minimizable:false,
					maximizable:false,
					collapsible:false,
					resizable:false,
					closable:false,
					cache:false,
					modal:true,
					onClose:function(){
						$(this).window('destroy');
					},
					onDestroy: function(){
						if(rollback) rollback();
						//removeScriptByediter();
					},
					onOpen:function(){
						$('#p'+id).progressbar({
							value: 0,
							onChange: function(value){
								//alert(value);
							}
						});
						self.start(time,id);
					}
			});
		}
		
	};
	this.start = function(time,id){
		if(time==-1){
			if(this.shieldTime==1){
				$.messager.progress('close');
			}else{
				var self = this;
				var s = function(){
					self.start(time,id);
				}
				setTimeout(s, 500);
			}
		}else{
			var value = $('#p'+id).progressbar('getValue');
			if (value < 100){
				if(this.shieldTime>=0 && this.shieldTime<time){
					value = this.shieldTime * Math.round(100/time);
				}else value=100;
				$('#p'+id).progressbar('setValue', value);
				var self = this;
				var s = function(){
					self.start(time,id);
				}
				setTimeout(s, 500);
			}else{
				$('#'+id).window('destroy');
			}
		}
	};
	
};





function UIDateTime(){
	/** 日期格式转换  使用在easyui-datebox*/
	this.dateformatter = function (date) {
		 var y = date.getFullYear();
		 var m = date.getMonth()+1;
		 var d = date.getDate();
		 return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
	}
	this.dateparser = function (s) {
		if (!s) return new Date();
		if(typeof(s)=='number'){
			return new Date(s);
		}else{
			var ss = s.split('-');
			if(!ss) return new Date();
			var y = parseInt(ss[0],10);
			var m = parseInt(ss[1],10);
			var d = parseInt(ss[2],10);
			if(ss.length==1){
				m = parseInt('01',10);
				d = parseInt('01',10);
			}else if(ss.length==2){
				d = parseInt('01',10);
			}
			if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
				return new Date(y,m-1,d);
			} else {
				return new Date();
			}			
		}
	},
	this.datetimeformatter = function(date,format) {
		var y = date.getFullYear();
		var m = date.getMonth() + 1;
		var d = date.getDate();
		var h = date.getHours();
		var mm = date.getMinutes();
		var s = date.getSeconds();
		var datestring = y+'';
		if(format=='y') return datestring;
		datestring += '-' + (m < 10 ? ('0' + m) : m);
		if(format=='m') return datestring;
		datestring += '-' + (d < 10 ? ('0' + d) : d);
		if(format=='d') return datestring;
		datestring += ' ' + (h < 10 ? ('0' + h) : h);
		if(format=='h') return datestring;
		datestring += ":" + (mm < 10 ? ('0' + mm) : mm);
		if(format=='mm') return datestring;
		datestring += ":" + (s < 10 ? ('0' + s) : s);
		return datestring;
	},
	this.datetimeparser = function (s) {
		if (!s) return new Date();
		if(typeof(s)=='number'){
			return new Date(s);
		}else{
			var ss;
			//2016-11-29T15:57:46.000+08:00
			if(s.indexOf('T')>-1){
				ss = (s.split('T'));
			}else{
				ss = (s.split(' '));
			}
			yms = (ss[0].split('-'));
			hms = (ss[1].split(':'));
			var y = parseInt(yms[0], 10);
			var m = parseInt(yms[1], 10);
			var d = parseInt(yms[2], 10);
			if(yms.length==1){
				m = parseInt('01',10);
				d = parseInt('01',10);
			}else if(yms.length==2){
				d = parseInt('01',10);
			}
			var h = parseInt(hms[0], 10);
			var mm = parseInt(hms[1], 10);
			var s = parseInt(hms[2], 10);
			if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
				return new Date(y, m - 1, d,h,mm,s);
			} else {
				return new Date();
			}
		}
	}
	/** 日期格式转换  使用在easyui-datetimebox*/
	this.timeformatter = function (date,showSeconds) {
		if (!date){return '';}
		var tt = [formatN(date.getHours()), formatN(date.getMinutes())];
		if (showSeconds){
			tt.push(formatN(date.getSeconds()));
		}
		return tt.join(':');
		
		function formatN(value){
			return (value < 10 ? '0' : '') + value;
		}
	}
	this.timeparser = function (s) {
		if (!s){return null;}
		var tt = s.split(':');
		return new Date(1900, 0, 0, 
			parseInt(tt[0],10)||0, parseInt(tt[1],10)||0, parseInt(tt[2],10)||0);
	}	
}

/**
 * 查询与重置
 */
function UISearchFrom(){
	var __oldParams = {};	
	var self = this;
	this.clearFormForGrid = function (grid,workTable,queryForm,noReload){
		var id = queryForm+workTable;
		var fields =$(queryForm).serializeArray(); //自动序列化表单元素为JSON对象
		var params = {};
		$.each( fields, function(i, field){
			if(field.value!='') {
				if(field.name.indexOf('symbol[')==0
						|| field.name.indexOf('type[')==0){
					params[field.name] = field.value;
				}
			}
		});
		$(queryForm).form('clear');
		$(queryForm).form('load',params);
		//$(workTable).datagrid('options').queryParams = __oldParams[queryForm];
		if(!noReload) $(workTable)[grid]('load',__oldParams[id]); //设置好查询参数 reload 一下就可以了
		delete __oldParams[id];
	}
	//表格查询
	this.searchForGrid = function (grid,workTable,queryForm,onBeforeSubmit){
		var id = queryForm+workTable;
		var oldParams = __oldParams[id];
		if(!__oldParams[id]){
			oldParams = $(workTable)[grid]('options').queryParams;
			__oldParams[id] = oldParams;
		} 
		var params = $.extend({},oldParams); //先取得 datagrid 的查询参数
		var fields =$(queryForm).serializeArray(); //自动序列化表单元素为JSON对象
		$.each( fields, function(i, field){
			if(field.value!='') params[field.name] = field.value; //设置查询参数
		}); 
		//====
		var f = function(name,p){
			if(name.indexOf(p)==0){
				if(params[name]===oldParams[name]){
					var field = name.replace(p,'').replace(']','');
					var symbol = 'symbol['+field+']';
					if(oldParams[symbol] && params[symbol]) 
						params[symbol] = oldParams[symbol];
					var type = 'type['+field+']';
					if(oldParams[type] && params[type]) 
						params[type] = oldParams[type];
				}
			}
		}
		for(var name in oldParams){
			f(name,'masteTable[');
			f(name,'slaveTable[');
			f(name,'otherTable[');
		}	
		//====
		if(onBeforeSubmit) onBeforeSubmit(params);
		$(workTable)[grid]('load',params); //设置好查询参数 reload 一下就可以了
		
	}
	//重置查询
	this.clearFormForTreegrid = function (workTable,queryForm,noReload){
		self.clearFormForGrid('treegrid',workTable,queryForm,noReload);
	}
    //表格查询
	this.searchForTreegrid = function (workTable,queryForm,onBeforeSubmit){
		self.searchForGrid('treegrid',workTable,queryForm,onBeforeSubmit);
	}
	//重置查询
	this.clearFormForDatagrid = function (workTable,queryForm,noReload){
		self.clearFormForGrid('datagrid',workTable,queryForm,noReload);
	}
    //表格查询
	this.searchForDatagrid = function (workTable,queryForm,onBeforeSubmit){
		self.searchForGrid('datagrid',workTable,queryForm,onBeforeSubmit);
	}
	//重置查询
	this.clearFormForDatalist = function (workTable,queryForm,noReload){
		self.clearFormForGrid('datalist',workTable,queryForm,noReload);
	}
    //表格查询
	this.searchForDatalist = function (workTable,queryForm,onBeforeSubmit){
		self.searchForGrid('datalist',workTable,queryForm,onBeforeSubmit);
	}
}


/**
 * 弹出窗口
 */
function UIShowWindow(){
	var __windowReturnValue = {};
	var __windowCloseFn = {};	

	this.showWindow = function(title,href,width,height,loadFn,closeFn){
		var id = getWindowID(href);
		$('body').append("<div id='" + id + "'></div>");
		$('#'+id).window({
					title:title,
					href:href,
					width:width,
					height:height,
					minimizable:false,
					maximizable:false,
					collapsible:false,
					resizable:true,
					cache:false,
					modal:true,
					method:'get',
					onClose:function(){
						$(this).window('destroy');
						if(__windowCloseFn[id]){
							__windowCloseFn[id]();
							delete __windowCloseFn[id];
						}
					},
					onDestroy: function(){
						//removeScriptByediter();
					},
					onLoad: function(){
						if(typeof(loadFn)=='function') loadFn();
					}
				});
		__windowCloseFn[id]=closeFn;
	}


	//关闭弹出窗口
	this.closeWindow = function(href,returnValue){
		var id = href;
		if(href.indexOf ('#')!=-1) {
			id = href;
		}else{
			id = getWindowID(href);
		}
		
		if(returnValue) __windowReturnValue[id] = returnValue;
		else if(__windowReturnValue[id]) delete __windowReturnValue[id];
		
		$('#'+id).window('destroy');
		if(__windowCloseFn[id]){
			__windowCloseFn[id](returnValue);
			delete __windowCloseFn[id];
		}
	}
	this.resizeWindow = function(href,options){
		var ops = $('#'+getWindowID(href)).window('options');
		var left = ops.left;
		var top = ops.top;
		$('#'+getWindowID(href)).window('resize',{
			width:options.width+15,
			height:options.height+42,
			left:left-options.width/2,
			top:top-options.height/2,
		});
	}
	var getWindowID = function(href){
		var url = href;
		if((x=href.indexOf('?'))!=-1) url = href.substring(0, x);
		var s = url.replace(".jsp","").replace(".html","").replace("\\","/").split("/");
		return "window_" + s[s.length-1];
	}
	this.getReturnValue = function (href){
		return __windowReturnValue[getWindowID(href)];
	}	
}	